<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <link rel="icon" href="../image/favicon.ico">
    <link rel="stylesheet" href="../library/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="../library/font-awesome/css/font-awesome.css" media="all">
    <link rel="stylesheet" href="../library/GridManager/index.css" media="all">
    <style>
        .gm-menu, .table-wrap {
            --gm-font-size: 13px;
        }

        .filters-body * {
            box-sizing: border-box !important;
        }
    </style>
</head>

<body style="margin:15px">
<form class="layui-form" lay-filter="query-form">
    <div class="layui-form-item">
        <div class="layui-col-sm10">
            <div class="layui-col-sm3">
                <div class="layui-input-inline" style="width:90%">
                    <input type="number" name="id" class="layui-input" placeholder="用户ID"/>
                </div>
            </div>

            <div class="layui-col-sm3">
                <div class="layui-input-inline" style="width:90%">
                    <input type="text" name="name" class="layui-input" placeholder="用户名"/>
                </div>
            </div>

            <div class="layui-col-sm3">
                <div class="layui-input-inline" style="width:90%">
                    <select name="gender" class="layui-select">
                        <option value="" selected>性别不限</option>
                        <option value="保密">保密</option>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
            </div>

            <div class="layui-col-sm3">
                <div class="layui-input-inline" style="width:90%">
                    <div id="more-filters" class="layui-input-inline" style="width:100%"></div>
                </div>
                <template id="filters-template">
                    <div class="filters-body" style="padding:10px">
                        <div class="layui-form-item">
                            <div class="layui-input-inline" style="width:100%">
                                <select name="status" class="layui-select" lay-filter="filters">
                                    <option value="" selected>状态不限</option>
                                    <option value="1">状态有效</option>
                                    <option value="2">状态无效</option>
                                </select>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <div class="layui-input-inline" style="width:100%">
                                <input type="number" name="id_gt" class="layui-input" placeholder="ID大于"/>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <div class="layui-input-inline" style="width:100%">
                                <input type="number" name="id_lt" class="layui-input" placeholder="ID小于"/>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <div class="layui-btn-group">
            <button type="submit" class="layui-btn" lay-submit lay-filter="query-submit">
                <i class="fa fa-search"></i> 搜索
            </button>
            <button type="button" class="layui-btn layui-btn-normal add-button">
                <i class="fa fa-plus"></i> 添加
            </button>
        </div>
    </div>
</form>

<div style="height:calc(100vh - 85px);margin-top:15px">
    <table id='main-table'></table>
</div>

<!--表单窗口-->
<template id="main-edit-win">
    <div style="padding:10px">
        <form id="main-edit-form" class="layui-form" lay-filter="main-edit-form">
            <input type="hidden" name="id" value="0"/>
            <div class="layui-form-item">
                <label class="layui-form-label">用户名</label>
                <div class="layui-input-block">
                    <input type="text" name="name" class="layui-input"
                           placeholder="请输入用户名" lay-verify="required"/>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">新密码</label>
                <div class="layui-input-block">
                    <input type="password" name="password" class="layui-input" placeholder="请输入新密码"/>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">新头像</label>
                <div class="layui-input-block">
                    <input type="file" name="header_file" placeholder="点击兄弟节点"
                           onchange="$(this).next().val($(this).val())" hidden/>
                    <input class="layui-input" style="cursor:pointer" placeholder="请选择新头像"
                           onclick="$(this).prev().click()" readonly/>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">性别</label>
                <div class="layui-input-block">
                    <select name="gender" lay-verify="required">
                        <option value="保密" selected>保密</option>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">角色</label>
                <div class="layui-input-block">
                    <div id="select-role"></div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">状态</label>
                <div class="layui-input-block">
                    <select name="status" lay-verify="required">
                        <option value="1" selected>有效</option>
                        <option value="2">无效</option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">签名</label>
                <div class="layui-input-block">
                    <textarea name="sign" class="layui-textarea" style="resize:none"
                              placeholder="请输入签名"></textarea>
                </div>
            </div>

            <div class="layui-form-item" style="text-align:center">
                <div style="margin:20px">
                    <button type="submit" class="layui-btn layui-btn-normal" lay-submit lay-filter="main-edit-ok">
                        <i class="fa fa-check"></i>确定
                    </button>

                    <button type="button" style="margin-left:50px" class="layui-btn layui-btn-warm"
                            onclick="layui.layer.closeAll()">
                        <i class="fa fa-close"></i>取消
                    </button>
                </div>
            </div>
        </form>
    </div>
</template>

<template id="detail-template">
    <div class="layui-inline">
        <img style="border-radius:5px;margin:20px;width:200px"
             alt="无法显示" src="data:image;base64,{{header}}"/>
    </div>
    <div class="layui-inline" style="vertical-align:top;margin:25px">
        <h2>{{name}}</h2>
        <hr/>
        <h3>性别：{{gender}}</h3>
        <br/>
        <h3>角色：{{role}}</h3>
        <br/>
        <h3>签名：{{sign}}</h3>
        <br/>
        <h3>更新时间：{{updated_at}}</h3>
    </div>
</template>

<script src="../library/jquery/jquery.js" charset="utf-8"></script>
<script src="../library/layui/layui.js" charset="utf-8"></script>
<script src="../library/xm-select/xm-select.js" charset="utf-8"></script>
<script src="../library/GridManager/index.js" charset="utf-8"></script>
<script src="../admin/common.js" charset="utf-8"></script>
<script type="application/javascript">
    $(function () {
        let filters = xmSelect.render({
            el: '#more-filters',
            tips: '更多条件',
            name: '',
            content: $('#filters-template').html(),
            model: {label: {block: {showIcon: false}}}
        });

        var params = getUrlParams();
        var defaultParam = layui.form.val('query-form');
        layui.form.val('query-form', getUrlParams(params));

        // 监听条件改变
        setFilterValue();
        layui.form.on('select(filters)', setFilterValue);
        $('.filters-body input').on('change', setFilterValue);

        // 监听按钮事件
        $('.add-button').on('click', openEditWin);
        layui.form.on('submit(query-submit)', function (form) {
            filters.closed();
            setUrlParams(form.field, defaultParam);
            GridManager.setQuery('main-table', form.field);
            return false;
        });

        createTable(layui.form.val('query-form'));
    });

    function setFilterValue() {
        let values = [];
        $('.filters-body').children().each(function (index, elem) {
            elem = $(elem);
            let selects = elem.find('.layui-this:not(.layui-select-tips)');
            if (selects.length) {
                let value = selects.text();
                values.push({name: value, value: value, selected: true});
            } else {
                elem.find('input').each(function (idx, input) {
                    if (input.value) {
                        let value = input.placeholder ? input.placeholder + ':' + input.value : input.value;
                        values.push({name: value, value: value, selected: true});
                    }
                });
            }
        });
        xmSelect.get('#more-filters', true).update({data: values});
        return true;
    }

    // 加载表格
    function createTable(params) {
        document.querySelector('#main-table').GM({
            gridManagerName: 'main-table',
            ajaxUrl: "../../api/user/query",
            query: params,
            ajaxData: gmAjaxData,
            ajaxType: 'POST',
            height: '100%',
            width: '100%',
            disableCache: false,
            supportAjaxPage: true,
            sizeData: [10, 20, 50, 100],
            supportCheckbox: false,
            supportMenu: true,
            useWordBreak: true,
            disableLine: true,
            disableBorder: true,
            supportAutoOrder: false,
            asyncTotals: {
                text: '加载中', handler: gmAjaxTotals
            },
            columnData: [{
                key: 'id', width: '100px', fixed: 'left',
                text: '用户ID', template: gmStrongTemplate
            }, {
                key: 'name', width: '200px', text: '用户名'
            }, {
                key: 'header', width: '200px', text: '用户头像',
                template: gmHeaderTemplate
            }, {
                key: 'status', width: '200px', text: '状态',
                template: statusTemplate
            }, {
                key: 'gender', width: '200px', text: '性别',
                template: genderTemplate
            }, {
                key: 'role', width: '200px', text: '角色'
            }, {
                key: 'sign', text: '签名',
                template: gmPreTemplate
            }, {
                key: '_operate_', width: '160px', fixed: 'right',
                text: '操作', template: rowOperates
            }],
            fullColumn: {
                useFold: true, fixed: 'left', bottomTemplate: function (row, index) {
                    var html = $('#detail-template').html().replace("{{header}}", row.header);
                    html = html.replace("{{name}}", row.name).replace("{{gender}}", row.gender);
                    html = html.replace("{{role}}", row.role).replace("{{sign}}", row.sign);
                    return html.replace("{{updated_at}}", formatDateTime(row.updated_at));
                }
            }
        });
    }

    function statusTemplate(cell, row, index, key) {
        var value = row[key] || 0;
        return {
            0: '<span style="color:white;background:#999;border-radius:5px;padding:3px">未知</span>',
            1: '<span style="color:white;background:#5b5;border-radius:5px;padding:3px">有效</span>',
            2: '<span style="color:white;background:#e88;border-radius:5px;padding:3px">无效</span>'
        }[value] || value;
    }

    function genderTemplate(cell, row, index, key) {
        var value = row[key] || '保密';
        return {
            保密: '<span style="color:white;background:#999;border-radius:5px;padding:2px">保密</span>',
            男: '<span style="color:white;background:#88e;border-radius:5px;padding:3px">男</span>',
            女: '<span style="color:white;background:#e88;border-radius:5px;padding:3px">女</span>'
        }[value] || value;
    }

    function gmHeaderTemplate(cell, row, index, key) {
        var value = row[key] || "";
        return value ? "<img style='width:80px;border-radius:40px' " +
            "src='data:image;base64," + value + "' alt=''/>" : ""
    }

    function rowOperates() {
        return '<button class="layui-btn layui-btn-normal layui-btn-sm" onclick="openEditWin(this)">' +
            '<i class="fa fa-pencil"></i> 修改</button>' +
            '<button class="layui-btn layui-btn-danger layui-btn-sm" onclick="deleteAction(this)">' +
            '<i class="fa fa-remove"></i> 删除</button>';
    }

    // 编辑提交按钮
    function editFormSubmit(form) {
        var data = form.field;
        data.id = parseInt(data.id) || 0;
        data.valid_status = parseInt(data.valid_status) || 0;
        $.ajax({
            url: "../../api/user/save",
            method: "post",
            processData: false,
            contentType: false,
            data: new FormData($('#main-edit-form')[0]),
            dataType: "json",
            success: function (result) {
                if (result && result.status < 400) {
                    layui.layer.closeAll();
                    GridManager.refreshGrid('main-table');
                    layui.layer.msg("保存成功", {icon: 1});
                } else {
                    layui.layer.msg(result.message, {icon: 2});
                }
            }
        });
        return false;
    }

    // 打开编辑窗口
    function openEditWin(e) {
        var data = GridManager.getRowData('main-table', getParentRow(e)) || {};
        layui.layer.open({
            type: 1,
            title: '<i class="fa fa-list"></i> ' + (data.id ? '修改用户 ' + data.id : '新增用户'),
            offset: '160px',
            area: '600px',
            content: $('#main-edit-win').html(),
            success: function () {
                xmSelect.render({
                    el: '#select-role',
                    name: 'role',
                    data: [{name: '管理员', value: '管理员'},
                        {name: '前端', value: '前端'},
                        {name: '后端', value: '后端'},
                        {name: '产品', value: '产品'},
                        {name: '测试', value: '测试'}]
                });
            }
        });
        data.header_file = "";
        layui.form.val('main-edit-form', data);
        // 获取下拉组件赋值，true表示获取单个
        xmSelect.get('#select-role', true).setValue((data.role || "").split(","));
        // 监听编辑提交
        layui.form.on('submit(main-edit-ok)', editFormSubmit);
        layui.form.render();
    }

    // 删除操作
    function deleteAction(e) {
        var data = GridManager.getRowData('main-table', getParentRow(e)) || {};
        layui.layer.confirm('你确定要删除' + data.id + '?', {
            title: '<i class="fa fa-remove"></i> 确认删除', icon: 3
        }, function () {
            $.ajax({
                url: "../../api/user/delete",
                method: "post",
                data: {id: data.id},
                dataType: "json",
                success: function (result) {
                    if (result && result.status < 400) {
                        layui.layer.closeAll();
                        GridManager.refreshGrid('main-table');
                        layui.layer.msg("删除成功", {icon: 1});
                    } else {
                        layui.layer.msg(result.message, {icon: 2});
                    }
                }
            });
        });
    }
</script>
</body>
</html>